package kr.co.goodwilldd.framework.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class ReloadAuthenticationListener implements
		ApplicationListener<ApplicationEvent> {

	@Autowired
	CustomUserDetailService customUserDetailService;

	@Autowired
	IAuthenticationFacade authenticationFacade;

	/**
	 * 로그인한 사용자에 대한 정보를 리로딩한다.
	 */
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ReloadAuthenticationEvent) {
			String username = (String) event.getSource();
			SecurityContextHolder.getContext()
					.setAuthentication(
							createNewAuthentication(
									authenticationFacade.getAuthentication(),
									username));
		}
	}

	protected Authentication createNewAuthentication(
			Authentication currentAuth, String username) {
		UserDetails newPrincipal = customUserDetailService
				.loadUserByUsername(username);
		UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
				newPrincipal, currentAuth.getCredentials(),
				newPrincipal.getAuthorities());
		newAuth.setDetails(currentAuth.getDetails());
		return newAuth;
	}

}
